<template>
  <div>
    <a-row>
      <a-button type="primary" @click="showModal(false)">新增</a-button>
      <a-button type="primary" @click="showModal(true)">修改</a-button>
      <a-button type="danger" @click="removeApp">删除</a-button>
      <a-button type="primary" @click="showConfigModal">环境变量</a-button>

      <!--      <a-button type="primary" @click="deployEnv">部署环境</a-button>-->
    </a-row>
    <a-row>
      <a-col :span="24">
        <a-table :columns="grid.columns"
                 :rowKey="record => record.id"
                 :dataSource="grid.data"
                 :pagination="grid.pagination"
                 :loading="grid.loading"
                 @change="handleTableChange"
                 :rowSelection="grid.rowSelection"
        >
            <span slot="action" slot-scope="text, record">
              <a :href="`${baseUrl}/api/downloadall/${record.name}`">{{record.name}}</a>
            </span>
        </a-table>
      </a-col>
    </a-row>

    <a-modal
      title="环境"
      :visible="visible"
      :maskClosable="false"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="form">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入环境名称' }]}
        ]"
          />
          <a-input
            v-decorator="[
          'keyName',
          {rules: [{ required: false, message: '请输入秘钥名' }]}
        ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!--配置项-->
    <a-modal
      title="配置项"
      :maskClosable="false"
      :visible="configVisible"
      @cancel="configHandleCancel"
      :destroyOnClose="true"
    >

      <a-row>
        <a-button type="primary" @click="showEditConfigModal(false)">新增</a-button>
        <a-button type="primary" @click="showEditConfigModal(true)">修改</a-button>
        <a-button type="primary" @click="removeItem">删除</a-button>
      </a-row>
      <a-row>
        <a-table :columns="configGrid.columns"
                 :rowKey="record => record.id"
                 :dataSource="configGrid.data"
                 :pagination="configGrid.pagination"
                 :loading="configGrid.loading"
                 @change="handleConfigGridChange"
                 :rowSelection="configGrid.rowSelection"
        >
        </a-table>
      </a-row>
      <template slot="footer">
        <a-button key="back" @click="configGridHandleCancel">关闭</a-button>
      </template>
    </a-modal>

    <!--编辑端口-->
    <a-modal
      title="映射端口"
      :maskClosable="false"
      :visible="editConfigVisible"
      @ok="handleEditConfigOk"
      @cancel="editConfigHandleCancel"
      :destroyOnClose="true"
    >
      <a-form :form="configForm">
        <a-form-item
          label="名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'key',
          {rules: [{ required: true, message: '请输入名称' }]}]"
          />
        </a-form-item>
        <a-form-item
          label="值"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
          'value',
          {rules: [{ required: true, message: '请输入值' }]}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
    import {getBaseUrl, getFetch, postFetch} from '@/util/fetch';

    export default {
        mounted() {
            this.fetch();
        },
        data() {
            return {
                baseUrl: getBaseUrl(),
                grid: {
                    columns: [
                        {
                            title: 'ID',
                            dataIndex: 'id'
                        }, {
                            title: '名称',
                            dataIndex: 'name',
                        },
                        {
                            title: '秘钥名',
                            dataIndex: 'keyName',
                        },
                        {
                            title: '操作',
                            key: 'action',
                            scopedSlots: { customRender: 'action' }
                        }
                    ],
                    loading: false,
                    data: [],
                    rowSelection: {
                        type: "radio",
                        selectedRowKeys: [],
                        onChange: this.onSelectChange,
                    },
                    selectedRows: [],
                    pagination: {
                        pageSize: 10,
                        current: 1
                    },
                },
                configGrid: {
                    loading: false,
                    columns: [
                        {
                            title: 'ID',
                            dataIndex: 'id'
                        }, {
                            title: '名称',
                            dataIndex: 'key',
                        }, {
                            title: '值',
                            dataIndex: 'value',
                        }
                    ],
                    data: [],
                    selectedRows: [],
                    rowSelection: {
                        type: "radio",
                        selectedRowKeys: [],
                        onChange: this.onConfigSelectChange,
                    },
                    pagination: {
                        pageSize: 10,
                        current: 1
                    },
                },
                form: this.$form.createForm(this),
                configForm: this.$form.createForm(this),
                ModalText: 'Content of the modal',
                visible: false,
                configVisible: false,
                editConfigVisible: false,
                confirmLoading: false,
                editApp: false,
                editConfig: false,
            }
        },
        methods: {
            showPortModal() {
                let that = this;
                if (this.grid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                that.mappingPortVisible = true;
                that.fetchConfigItem();
            },
            handleConfigGridChange() {

            },
            configGridHandleCancel() {
                this.configVisible = false;
            },
            fetchConfigItem() {
                let that = this;
                let appEnvId = that.grid.selectedRows[0].id;
                that.configGrid.loading = true;
                getFetch("/api/envConfigItem?env.id=" + appEnvId + "&page=" + that.configGrid.pagination.current + "&size=" + that.configGrid.pagination.pageSize).then((data) => {
                    const pagination = { ...that.configGrid.pagination };
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    pagination.total = data.data.totalElements;
                    that.configGrid.loading = false;
                    that.configGrid.data = data.data.content;
                    that.configGrid.pagination = pagination;
                });
            },
            handleEditConfigOk(e) {
                console.log("------");
                e.preventDefault();
                let that = this;
                this.configForm.validateFields((err, values) => {
                    if (!err) {
                        if (this.editConfig) {
                            values.id = this.configGrid.selectedRows[0].id;
                        }
                        let url = "/api/envConfigItem";
                        if (this.editConfig) {
                            url += "/update";
                        }
                        values.env = that.grid.selectedRows[0];
                        postFetch(url, values).then((data) => {
                            this.configForm.resetFields();
                            this.editConfigVisible = false;
                            this.fetchConfigItem();
                            this.configGrid.rowSelection.selectedRowKeys = [];
                            this.configGrid.selectedRows = [];
                        });
                    } else {
                        this.$message.error("字段有错误");
                    }
                });
            },
            editConfigHandleCancel() {
                console.log('Clicked cancel button');
                this.editConfigVisible = false;
            },
            onConfigSelectChange(selectedRowKeys, selectedRows) {
                this.configGrid.selectedRows = selectedRows;
                this.configGrid.rowSelection.selectedRowKeys = selectedRowKeys;
            },

            removeApp() {
                if (this.grid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                let that = this;
                this.$confirm({
                    title: '确认',
                    content: '你确认要删除吗?',
                    onOk() {
                        getFetch("/api/env/" + that.grid.selectedRows[0].id + "/delete").then((data) => {
                            that.fetch();
                        });
                    },
                    onCancel() {
                    },
                });
            },
            removeItem() {
                if (this.configGrid.selectedRows.length !== 1) {
                    this.$message.warn("请选中一行");
                    return;
                }
                const that = this;
                this.$confirm({
                    title: '确认',
                    content: '你确认要删除吗?',
                    onOk() {
                        getFetch("/api/envConfigItem/" + that.configGrid.selectedRows[0].id + "/delete").then((data) => {
                            that.fetchConfigItem();
                        });
                    },
                    onCancel() {
                    },
                });
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.grid.selectedRows = selectedRows;
                this.grid.rowSelection.selectedRowKeys = selectedRowKeys;
            },

            showModal(edit) {
                if (edit) {
                    this.editApp = true;
                    if (this.grid.selectedRows.length === 0) {
                        this.$message.warn("请选中行");
                    } else if (this.grid.selectedRows.length > 1) {
                        this.$message.warn("请选中一行");
                    } else {
                        let row = this.grid.selectedRows[0];
                        setTimeout(() => {
                            this.form.setFieldsValue({
                                name: row.name,
                                keyName: row.keyName
                            });
                        }, 0);
                        this.visible = true
                    }
                } else {
                    this.editApp = false;
                    this.form.resetFields();
                    this.visible = true
                }
            },
            showConfigModal() {
                if (this.grid.selectedRows.length === 0) {
                    this.$message.warn("请选中行");
                    return;
                }
                this.fetchConfigItem();
                this.configVisible = true
            },
            handleOk(e) {
                console.log("------");
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        if (this.editApp) {
                            values.id = this.grid.selectedRows[0].id;
                        }
                        let url = "/api/env";
                        if (this.editApp) {
                            url += "/update";
                        }
                        postFetch(url, values).then((data) => {
                            this.form.resetFields();
                            this.visible = false;
                            this.fetch();
                            this.grid.rowSelection.selectedRowKeys = [];
                            this.grid.selectedRows = [];
                        });
                    }
                });
            },
            handleCancel(e) {
                console.log('Clicked cancel button');
                this.visible = false;
            },
            configHandleCancel(e) {
                console.log('Clicked cancel button');
                this.configVisible = false;
            },
            showEditConfigModal(edit) {
                if (edit) {
                    this.editConfig = true;
                    if (this.configGrid.selectedRows.length === 0) {
                        this.$message.warn("请选中行");
                    } else if (this.configGrid.selectedRows.length > 1) {
                        this.$message.warn("请选中一行");
                    } else {
                        let row = this.configGrid.selectedRows[0];
                        setTimeout(() => {
                            this.configForm.setFieldsValue({
                                key: row.key,
                                value: row.value,
                            });
                        }, 0);
                        this.editConfigVisible = true;
                    }
                } else {
                    this.editConfig = false;
                    this.configForm.resetFields();
                    this.editConfigVisible = true;
                }
            },
            handleTableChange(pagination, filters, sorter) {
                this.grid.pagination.current = pagination.current;
                this.grid.pagination.pageSize = pagination.pageSize;
                this.fetch();
            },
            fetch() {
                let that = this;
                that.grid.loading = true;
                getFetch("/api/env?page=" + that.grid.pagination.current + "&size=" + that.grid.pagination.pageSize).then((data) => {
                    const pagination = { ...that.grid.pagination };
                    // Read total count from server
                    // pagination.total = data.totalCount;
                    pagination.total = data.data.totalElements;
                    that.grid.loading = false;
                    that.grid.data = data.data.content;
                    that.grid.pagination = pagination;
                });
            }
        },
    }
</script>
